package com.caffeinatedbliss.nanowrimo.servlet;

import com.caffeinatedbliss.nanowrimo.Graph;
import com.caffeinatedbliss.nanowrimo.NanoWebserviceUtils;
import org.nanowrimo.ws.NanowrimoWebServiceAPI;
import org.nanowrimo.ws.domain.UserSummary;
import org.nanowrimo.ws.domain.WordCountListEntry;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: Paul Hawke
 * Date: Jun 18, 2006
 * Time: 6:01:42 PM
 * To change this template use File | Settings | File Templates.
 */
public class NanowrimoGraph extends HttpServlet {
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    UrlProcessor processor = new UrlProcessor(request);
    int goal = processor.getGoal();
    String uid = processor.getFirstId();

    Graph graph;
    if (uid != null) {
      try {
        NanowrimoWebServiceAPI api = new NanowrimoWebServiceAPI();
        UserSummary summary = api.getUserHistory(Integer.parseInt(uid));
        if (goal == 50000 && summary.getGoal() != 50000){
          goal = summary.getGoal();
        }
        WordCountListEntry[] entries = summary.getEntries();
        graph = new Graph(NanoWebserviceUtils.convertToAmountWritten(entries), goal);
      } catch (NumberFormatException e) {
        graph = new Graph("", goal);
      }
    } else {
      String history = request.getParameter("history");
      graph = new Graph(history, goal);
    }
    response.setContentType("image/png");
    OutputStream os = response.getOutputStream();
    ImageIO.write(graph.getGraphImage(), "png", os);
    os.close();
  }
}
